//
//  WishViewController.m
//  TinyFortune
//
//  Created by lc on 16/6/23.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "WishViewController.h"
#import "wishCell.h"
#import "addWishViewController.h"
#import "wishModel.h"

NSString *const whishCellIdentifier = @"whish";
@interface WishViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    addWishViewController *_addWish;
}
@property (weak, nonatomic) IBOutlet UITableView *wishTableView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation WishViewController
#pragma mark - 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = [NSMutableArray new];
    }
    return _dataArray;
}
#pragma mark - 生命周期
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -createUI
- (void)createUI{
    //实例化导航条
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    [self.navigationItem setLeftBarButtonItem:leftBar];
    self.navigationController.navigationBar.translucent = NO ;
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:86/255.0f green:202/255.0f blue:255/255.0f alpha:0.5]];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
   // UIBarButtonItem *rightEditBar = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit:)];
    UIBarButtonItem *rightAddBar = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"add"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]style:UIBarButtonItemStylePlain target:self action:@selector(add:)];
   // [self.navigationItem setRightBarButtonItems:@[rightAddBar]];
    [self.navigationItem setRightBarButtonItem:rightAddBar];
    [self setTitle:@"心愿礼盒"];
    //添加滑动手势
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(rightGo)];
    [self.view addGestureRecognizer:rightSwip];
    [rightSwip setDirection:UISwipeGestureRecognizerDirectionRight];
    
    _wishTableView.backgroundColor = [UIColor whiteColor];
    [_wishTableView registerNib:[UINib nibWithNibName:@"wishCell" bundle:nil] forCellReuseIdentifier:whishCellIdentifier];
    _wishTableView.delegate = self ;
    _wishTableView.dataSource = self ;
    [_wishTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
}
#pragma mark - tableView协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  140;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    wishCell *cell = [tableView dequeueReusableCellWithIdentifier:whishCellIdentifier forIndexPath:indexPath];
    wishModel *model = self.dataArray[indexPath.row];
    cell.model = model ;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
#pragma  mark -打开照相机
- (void)openCamera{
    BOOL ret = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    //判断是否支持相机
    if (ret) {
        UIImagePickerController *picker = [UIImagePickerController new];
        //设置图片资源类型
        [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.delegate = self;
        
        //显示图片选择器
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"失败" message:@"科科，主人的手机不支持照相功能啊" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)openPhoto{
    UIImagePickerController *picker =[UIImagePickerController new];
    [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    picker.delegate = self ;
    picker.allowsEditing = YES ;
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma  mark - 实现选中图片协议
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
  
    _addWish = [addWishViewController new];
    _addWish.image = image ;
    
    //让图片选择器消失
    
    [picker dismissViewControllerAnimated:YES completion:nil];
   [self.navigationController pushViewController:_addWish animated:YES];
    
    
}

#pragma mark - 点击事件
//添加点击事件
- (void)add:(UIBarButtonItem *)sender{
    UIAlertController *talkAlert = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    //从相册中选择
    UIAlertAction *chooseAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self openPhoto];
    }];
    //将action放在controller上
    [talkAlert addAction:takePhotoAction];
    [talkAlert addAction:chooseAction];
    
    [self presentViewController:talkAlert animated:YES completion:nil];
    
    

}
- (void)edit:(UIBarButtonItem *)sender{
    
}
- (void)rightGo{
    [self cancel];
}
- (void)cancel{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 数据相关
- (void)requestData{
    AVUser *user = [AVUser currentUser];
    //从心愿礼盒表单查询到需要的数据
    AVQuery *query = [AVQuery queryWithClassName:@"whish"];
    [query whereKey:@"user" containedIn:@[user.mobilePhoneNumber,[user objectForKey:@"lovers"]]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSDictionary *dic = [NSDictionary new];
        for (AVObject *object in objects) {
            //手动解析
            dic = @{@"file":[object objectForKey:@"wishId"],
                    @"user":[object objectForKey:@"user"],
                    @"title":[object objectForKey:@"title"],
                    @"desc":[object objectForKey:@"desc"]};
            wishModel *model = [[wishModel alloc]initWithDict:dic];
            [self.dataArray addObject:model];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.wishTableView reloadData];
        });
        
    }];

}
@end
